import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_first_one/components/story_card.dart';
import 'package:flutter_first_one/util/page_load.dart';
import 'package:flutter_first_one/custom_behavior/scroll_behavior.dart';

class StoryCardList extends StatefulWidget {
  final Future<dynamic> Function(Map<String, dynamic>) requestApi;
  final Map<String, dynamic> params;
  const StoryCardList(
      {super.key, required this.requestApi, required this.params});

  @override
  // ignore: library_private_types_in_public_api
  _StoryCardListState createState() => _StoryCardListState();
}

class _StoryCardListState extends State<StoryCardList> {
  PageLoad pageLoad = PageLoad();

  final ScrollController _scrollController =
      ScrollController(); //监听下拉框的状态（触底对象）

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 给触底对象添加事件
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        // 触底触发的方法
        _getMoreData();
      }
    });
    // 加载分页
    pageLoad.loadData(widget.requestApi, getParams: widget.params);
  }

  Future _getMoreData() async {
    // 触发加载更多
    pageLoad.nextPage();
  }

  @override
  Widget build(BuildContext context) {
    final double SW = MediaQuery.of(context).size.width / 2;
    // 使用自定义class取消list滚动效果
    return CusScrollBehavior(
        child: CustomScrollView(
      physics: const ClampingScrollPhysics(),
      // 监听滚动条
      controller: _scrollController,
      //
      shrinkWrap: true,
      // 自定义子组件，但必须是Sliver开头组件
      slivers: [
        // 相当于GridView
        Obx(() => SliverGrid.builder(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2, // 一行放两个组件
                mainAxisExtent: SW + 100, // here set custom Height You Want
              ),
              itemCount: pageLoad.list.length, // 替换成你的数据源长度
              itemBuilder: (BuildContext context, int index) {
                return StoryCard(item: pageLoad.list[index]);
              },
            )),
        // 底部状态栏
        Obx(() => ListBottomStatus(
              loadComplete: pageLoad.loadComplete.value,
              isLoading: pageLoad.isLoading.value,
              listLength: pageLoad.list.length,
            ))
      ],
    ));
  }
}

// 底部状态栏
class ListBottomStatus extends StatelessWidget {
  final bool isLoading;
  final bool loadComplete;
  final int listLength;
  const ListBottomStatus(
      {super.key,
      required this.isLoading,
      required this.loadComplete,
      required this.listLength});

  statusWidget() {
    if (isLoading) {
      return const CircularProgressIndicator(
        valueColor:
            AlwaysStoppedAnimation<Color>(Color.fromRGBO(255, 152, 44, 0.8)),
        strokeWidth: 6, // 设置圆圈宽度
      );
    } else if (listLength == 0) {
      return const Text('暂无数据');
    } else if (loadComplete) {
      return const Text('没有更多了');
    }
  }

  @override
  Widget build(BuildContext context) {
    // 相当于Contain
    return SliverToBoxAdapter(
      child: SizedBox(
        height: 60,
        child: Center(
          child: statusWidget(),
        ),
      ),
    );
  }
}
